package com.vrv.netmgr.alarm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.GlobalConstants;
import com.vrv.common.UrlPrefix;
import com.vrv.common.listview.ListViewAdapter;
import com.vrv.common.listview.ListViewUtil;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.common.util.JsonUtil;
import com.vrv.netmgr.R;
import com.vrv.netmgr.assets.AdvanceSofterwareQueryActivity;
import com.vrv.netmgr.strategy.SWSetupMonitorActivity;
import com.vrv.netmgr.vo.SerializableDeviceIPOccupyQry;
/**
 * @Description 设备审计
 * @author yzj
 * @date
 * 
 */
public class RelateAuditQryActivity extends Activity {
	// 存储数据的数组列表
	private ArrayList<HashMap<String, Object>> listData = new ArrayList<HashMap<String,Object>>();
	private ListView listView;
	private ListAdapter adapter = new ListAdapter(); 
	private ListViewItemClick listItemClk = new ListViewItemClick();
	//
	public String IP_ADDRESS;
	//
	private View loadMoreView;
	//总记录数
	public int RECORD_COUNT;
	//当前页号
	public int CUR_INDEX;
	//等待对话框
	private ProgressDialog progressDialog;
	//查询成功
	private static final int QUERY = 3;
	private static final int NET_ERR = 4;
	private static final int QRY_REGIST = 5;
	private static final int QRY_UNREGIST = 6;
	private static final int QUERY_BY_IP = 7;
	//通过点击按钮查询标记
	private boolean qryByBtnFlag = false;
	//
	private boolean type = true;
	// PopWindow检索条件相关
	private ImageButton moreFuncBtn;
	private PopupWindow pwMyPopWindow;
	private ListView lvPopupList;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.assets_list_page);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tools_title);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		//
		init();
		//开始查询数据
		progressDialog = ProgressDialog.show(RelateAuditQryActivity.this, "", "查询中...", true, true);
		new Thread(new Runnable() {
			@Override
			public void run() {
				getDataFromServer(0, true, true, null);
				//返回数据成功消息
				handler.sendEmptyMessage(QUERY);
			}
		}).start();
	}
	/**listview背景设置*/
	private LinearLayout listBackView;
	
	/**
	 * 处理器
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
			case QUERY:
				findViews();
				/** listview背景设置 */
				listBackView.setVisibility(listView.getVisibility());
				break;
			case NET_ERR:
				Toast.makeText(RelateAuditQryActivity.this, "网络连接失败",Toast.LENGTH_LONG).show();
				break;
			case QRY_REGIST:
				if(RECORD_COUNT == 0){
					listView.setVisibility(View.INVISIBLE);
					break;
				}else listView.setVisibility(View.VISIBLE);
				if (RECORD_COUNT > ListViewUtil.PAGESIZE)
					loadMorePage(true, true, null);
				adapter.setNetDur(true);
				listItemClk.setNetDur(true);
				adapter.clear();
				initializeAdapter();
				//
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				/** listview背景设置 */
				listBackView.setVisibility(listView.getVisibility());
				break;
			case QRY_UNREGIST:
				if(RECORD_COUNT == 0){
					listView.setVisibility(View.INVISIBLE);
					break;
				}else listView.setVisibility(View.VISIBLE);
				if (RECORD_COUNT > ListViewUtil.PAGESIZE)
					loadMorePage(false, false, null);
				adapter.setNetDur(false);
				listItemClk.setNetDur(false);
				adapter.clear();
				initializeAdapter();
				//
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				/** listview背景设置 */
				listBackView.setVisibility(listView.getVisibility());
				break;
			case QUERY_BY_IP:
				qryByBtnFlag = true;
				if (RECORD_COUNT > 0) {
					listView.removeFooterView(loadMoreView);
					listView.setVisibility(View.VISIBLE);
					if (RECORD_COUNT > ListViewUtil.PAGESIZE){
						String deviceIP = msg.getData().getString("deviceIP");
						loadMorePage(type, true, deviceIP);
					}
					initializeAdapter();
					adapter.notifyDataSetChanged();
				} else listView.setVisibility(View.GONE);
				/** listview背景设置 */
				listBackView.setVisibility(listView.getVisibility());
				break;
			}
		}
	};
	//
	private void init(){
		setTitle();
		IP_ADDRESS = this.getString(R.string.ip_address);
		
		listBackView = (LinearLayout) findViewById(R.id.list_background);
	}
	//初始化listview的适配器
	public void initializeAdapter() {
		for (int i = 0; i < listData.size(); i++) {
			adapter.addItem(listData.get(i));
		}
	}
	//添加监听
	private class ListViewItemClick implements AdapterView.OnItemClickListener {
		@SuppressWarnings("unused")
		private boolean netDurIsZero;

		public void setNetDur(boolean netDurIsZero) {
			this.netDurIsZero = netDurIsZero;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			HashMap<String, Object> hashMap = adapter.getData(arg2);
			//
			SerializableDeviceIPOccupyQry serializable = new SerializableDeviceIPOccupyQry();
			serializable.setIP_ADDRESS(hashMap.get(IP_ADDRESS).toString());
			//
			Intent intent = new Intent(RelateAuditQryActivity.this, AuditInfoActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("info", serializable);
			intent.putExtras(bundle);
			startActivity(intent);
		}
	}
	public void loadMorePage(final boolean netDurIsZero, final boolean byDeviceIP, final String deviceIP) {
		loadMoreView = getLayoutInflater().inflate(R.layout.list_page_load, null);
		final Button loadNextButton = (Button) loadMoreView
				.findViewById(R.id.loadNextButton);
		final Button loadPreButton = (Button) loadMoreView
				.findViewById(R.id.loadPreButton);
		loadNextButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (loadNextButton.getText().equals("查看下一页")) {
					loadNextButton.setText("正在加载中..."); // 设置按钮文字
					loadNextButton.setEnabled(false);
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							loadMoreData(true, netDurIsZero, byDeviceIP, deviceIP);
							adapter.notifyDataSetChanged();
							loadNextButton.setText("查看下一页"); // 恢复按钮文字
							if ((CUR_INDEX + 1) * ListViewUtil.PAGESIZE >= RECORD_COUNT)
								loadNextButton.setVisibility(View.GONE);
							if (CUR_INDEX == 1)
								loadPreButton.setVisibility(View.VISIBLE);
							loadNextButton.setEnabled(true);
						}
					}, 0);
				}
			}
		});
		loadPreButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (loadPreButton.getText().equals("查看上一页")) {
					loadPreButton.setText("正在加载中..."); // 设置按钮文字
					loadPreButton.setEnabled(false);
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							loadMoreData(false, netDurIsZero, byDeviceIP, deviceIP);
							adapter.notifyDataSetChanged();
							loadPreButton.setText("查看上一页"); // 恢复按钮文字
							if (CUR_INDEX == 0)
								loadPreButton.setVisibility(View.GONE);
							if ((CUR_INDEX + 2) * ListViewUtil.PAGESIZE >= RECORD_COUNT)
								loadNextButton.setVisibility(View.VISIBLE);
							loadPreButton.setEnabled(true);
						}
					}, 0);
				}
			}
		});
		listView.addFooterView(loadMoreView); // 设置列表底部视图
	}
	//加载更多数据
	private void loadMoreData(boolean pageDown, boolean netDurIsZero, boolean byDeviceIP, String deviceIP) {
		int index;
		if (pageDown)
			index = CUR_INDEX + 1;
		else
			index = CUR_INDEX - 1;
		listData.clear();
		adapter.clear();
		getDataFromServer(index, netDurIsZero, byDeviceIP, deviceIP);
		int datasize = listData.size();
		for (int i = 0; i < datasize; i++)
			adapter.addItem(listData.get(i));
	}
	/**
	 * 查询所有数据
	 * @param pageNum
	 */
	public void getDataFromServer(int pageNum,  boolean netDurIsZero, boolean byDeviceIP, String deviceIP) {
		/**查询条件*/
		Map<String, String> map = new HashMap<String, String>();
		/**Map<String, Object> map = new HashMap<String, Object>();*/
		
		map.put(GlobalConstants.PAGE_NUM, pageNum + "");
		map.put(GlobalConstants.REG_ASSETS, GlobalConstants.ASSETS_REGISTERED + "");
		if(byDeviceIP)
			map.put(GlobalConstants.DEVICE_IP, deviceIP);
		/**查询结果*/
		boolean retVal = qrynetDurIsZero(map, netDurIsZero);
		if (!retVal) 
			/**查询失败消息*/
			handler.sendEmptyMessage(NET_ERR);
	}

	public boolean qrynetDurIsZero(Map<String, String> map, boolean netDurIsZero) {
		boolean retVal = false;
		HttpClientToServer httpClientToServer = new HttpClientToServer();
		String urlPrefix = new UrlPrefix(getApplicationContext())
				.getUrlPrefix();
		String urlAddr = urlPrefix + "/deviceInfo/jsonIPList.do?" 
				+(netDurIsZero ? "classId=1&registered=1" : "classId=1&registered=0");
		String response = httpClientToServer.doPost(urlAddr, map);

		if (HttpClientToServer.DO_POST_ERR.equals(response)
				|| HttpClientToServer.DO_POST_EXCEPT.equals(response))
			return retVal;
		try {
			JSONTokener jsonParser = new JSONTokener(response);
			JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
			retVal = jsonObj.getBoolean("success");

			if (!retVal)
				return retVal;
			int count = jsonObj.getInt("totalRecords");

			RECORD_COUNT = count;
			if (count < 1)
				return retVal;
			JSONArray jArr = jsonObj.getJSONArray("records");
			int jArrLen = jArr.length();

			if (jArrLen > 0) {
				CUR_INDEX = Integer.parseInt(map.get(GlobalConstants.PAGE_NUM));

			}
			for (int i = 0; i < jArr.length(); i++) {
				JSONObject jObj = (JSONObject) jArr.opt(i);
				HashMap<String, Object> myMap = new HashMap<String, Object>();
				myMap.put(IP_ADDRESS, JsonUtil.getJsonString(jObj, "ipaddres"));
				listData.add(myMap);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return retVal;
	}

	public void setTitle() {
		TextView title = (TextView) findViewById(R.id.title_text);
		title.setText("设备审计");

		/**
		 * 返回按钮
		 */
		ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
	}

	public void findViews() {
		iniPopupWindow();
		// 更多操作按钮
		moreFuncBtn = (ImageButton) findViewById(R.id.moreFunctionBtn);
		moreFuncBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (pwMyPopWindow.isShowing()) {
					pwMyPopWindow.dismiss();// 关闭
				} else {
					pwMyPopWindow.showAsDropDown(moreFuncBtn);// 显示
				}
			}
		});
		if(listView == null){
			//搜索输入框
			EditText edit = (EditText)findViewById(R.id.assets_conditionQry);
			//搜索按钮
			ImageView search_btn = (ImageView)findViewById(R.id.search_go_btn);
			edit.setHint(R.string.input_device_ip);
			
//			/**查询条件添加事件*/
//			edit.addTextChangedListener(new MyTextWatcher(edit, search_btn));
			/**查询按钮添加事件*/
			search_btn.setOnClickListener(new ClickSearchBtnListener(edit, search_btn));
			
			listView = (ListView) findViewById(R.id.assets_lv_id);
		}
		if (RECORD_COUNT > 0) {
			listView.removeFooterView(loadMoreView);
			listView.setVisibility(View.VISIBLE);
			if (RECORD_COUNT > ListViewUtil.PAGESIZE)
				loadMorePage(type, false, null);
			initializeAdapter();
			if (listView.getAdapter() == null)
				listView.setAdapter(adapter);
			else adapter.notifyDataSetChanged();
			listView.setOnItemClickListener(new ListViewItemClick());
		}
	}
	
	/**
	 * 查询按钮事件处理
	 * @author zxb
	 *
	 */
	private class ClickSearchBtnListener implements View.OnClickListener{
		
		EditText edit;
		ImageView search_btn;
		
		ClickSearchBtnListener(EditText edit, ImageView search_btn){
			this.edit = edit;
			this.search_btn = search_btn;
		}

		@Override
		public void onClick(View v) {
			final String editVal = edit.getText().toString();
			listData.clear();
			adapter.clear();
			progressDialog = ProgressDialog.show(RelateAuditQryActivity.this, "", "查询中...", true, true);
			search_btn.setEnabled(false);
			new Handler().post(new Runnable() {
				@Override
				public void run() {
					getDataFromServer(0, true, true, editVal);
					Message msg = new Message();
					msg.what = QUERY_BY_IP;
					Bundle data = new Bundle();
					data.putString("deviceIP", editVal);
					msg.setData(data);
					handler.sendMessage(msg);
					search_btn.setEnabled(true);
				}
			});
		}		
	}

	private void iniPopupWindow() {
		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.title_func_popupwindow, null);
		lvPopupList = (ListView) layout.findViewById(R.id.lv_popup_list);
		pwMyPopWindow = new PopupWindow(layout);
		pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
        		RelateAuditQryActivity.this, R.layout.list_item_popupwindow,
				R.id.tv_list_item, getResources().getStringArray(
						R.array.registType));
		lvPopupList.setAdapter(arrayAdapter);
		lvPopupList.setOnItemClickListener(new ClickPopupItemListener(arrayAdapter));
		// 控制popupwindow的宽度和高度自适应
		lvPopupList.measure(View.MeasureSpec.UNSPECIFIED,
				View.MeasureSpec.UNSPECIFIED);
		pwMyPopWindow.setWidth(lvPopupList.getMeasuredWidth());
		// pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight()) * 3);
		pwMyPopWindow.setHeight(LayoutParams.WRAP_CONTENT);
		// 控制popupwindow点击屏幕其他地方消失
		pwMyPopWindow.setBackgroundDrawable(this.getResources().getDrawable(
				R.drawable.bg_popupwindow));
		// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
		pwMyPopWindow.setOutsideTouchable(true);
    }
	private class ClickPopupItemListener implements AdapterView.OnItemClickListener{
		ArrayAdapter<String> arrayAdapter;
		ClickPopupItemListener(ArrayAdapter<String> arrayAdapter){
			this.arrayAdapter = arrayAdapter;
		}
		@Override
		public void onItemClick(AdapterView<?> parent, View view,
				final int position, long id) {
			pwMyPopWindow.dismiss();
			if (loadMoreView != null)
				listView.removeFooterView(loadMoreView);
			listData.clear();
			if (position == 0) {
				progressDialog = ProgressDialog.show(
						RelateAuditQryActivity.this, "", "查询中...", true, true);
				new Thread(new Runnable() {
					@Override
					public void run() {
						type = true;
						getDataFromServer(0, true, true, null);
						handler.sendEmptyMessage(QRY_REGIST);
					}
				}).start();
			} else if (arrayAdapter.getCount() - 3 == position) {
				Intent intent = new Intent(RelateAuditQryActivity.this,
						AdvanceSofterwareQueryActivity.class);
				startActivity(intent);
			} else {
				progressDialog = ProgressDialog.show(
						RelateAuditQryActivity.this, "", "查询中...", true, true);
				new Thread(new Runnable() {
					@Override
					public void run() {
						type = false;
						getDataFromServer(0, false, false, null);
						handler.sendEmptyMessage(QRY_UNREGIST);
					}
				}).start();
			}
			Toast.makeText(RelateAuditQryActivity.this,
					"" + arrayAdapter.getItem(position).toString(),
					Toast.LENGTH_LONG).show();
		}
	}

	private class ListAdapter extends ListViewAdapter {
		@SuppressWarnings("unused")
		private boolean netDurIsZero;

		public void setNetDur(boolean netDurIsZero) {
			this.netDurIsZero = netDurIsZero;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			final HashMap<String, Object> hashMap = getData(position);
			if (view == null){
				view = LayoutInflater.from(RelateAuditQryActivity.this).inflate(R.layout.deviceipoccupyqry_listpage_item, null);
			}
			/**默认背景色设置*/
			view.setBackgroundResource(R.drawable.list_item_state1);
			/**双行背景色设置*/
			if (position % 2 == 0) {
				view.setBackgroundResource(R.drawable.list_item_state);
			}

			TextView ip = (TextView) view.findViewById(R.id.tv_ip);
			ip.setText(hashMap.get(IP_ADDRESS).toString());
			return view;
		}
	}
	@Override
	public void onBackPressed() {
		finish();
		overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
		super.onBackPressed();
	}
}
